package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.api.domain.SkuPriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-11-12
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getTopSale() {

        return baseMapper.getTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {

        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId,skuId)
                .select(ProductSku::getSalePrice,ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);

        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;

    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {

        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId,id)
                .select(ProductSku::getId,ProductSku::getSkuSpec);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

        HashMap<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item->{
            skuSpecValueMap.put(item.getSkuSpec(),item.getId());
        });
        return skuSpecValueMap;
    }

    @Override
    public ProductSku getProductSku(Long skuId) {
        log.info(Thread.currentThread().getName()+"获取商品sku");
        try {
            //从缓存中获取数据
            String dataKey = "product:sku:" + skuId;
            ProductSku productSku = (ProductSku)redisTemplate.opsForValue().get(dataKey);
            //命中缓存
            if (productSku!=null){
                log.info(Thread.currentThread().getName()+"命中缓存");
                return productSku;
            }

            String lockKey="product:sku:lock:"+skuId;
            String lockValue = UUID.randomUUID().toString().replaceAll("-", "");
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 10, TimeUnit.SECONDS);
            if (flag){

                try {

                    productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                    if (productSku!=null){
                        return productSku;
                    }

                    productSku = baseMapper.selectById(skuId);

                    long ttl=productSku==null?60:60*10;
                    if (productSku==null){
                        productSku=new ProductSku();
                    }
                    redisTemplate.opsForValue().set(dataKey,productSku,ttl, TimeUnit.SECONDS);
                    return productSku;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    String script = """
                            if redis.call('get', KEYS[1]] == ARGV[1] then
                                return redis.call('del', KEYS[1])
                            else
                                return 0
                            end
                            """;
                    DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(script);
                    redisScript.setResultType(Boolean.class);
                    redisTemplate.execute(redisScript, Arrays.asList(lockKey),lockValue);
                }
            }else {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return this.getProductSku(skuId);
            }
        } catch (RuntimeException e) {
            return baseMapper.selectById(skuId);
        }


    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {

        //根据skuid列表批量查询商品的最新价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSku::getId,skuIdList);
        queryWrapper.select(ProductSku::getId,ProductSku::getSalePrice);

        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        return productSkuList.stream().map(productSku -> {
            SkuPriceVo skuPriceVo = new SkuPriceVo();
            skuPriceVo.setSkuId(productSku.getId());
            skuPriceVo.setSalePrice(productSku.getSalePrice());
            return skuPriceVo;
        }).collect(Collectors.toList());
    }
}
